package com.zbkj.admin.disruptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.lmax.disruptor.EventHandler;
import com.zbkj.admin.boot.redisson.locker.RedisLockClient;
import com.zbkj.admin.listener.OrderCreateListener;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单消费
 */
@Slf4j
public class OrderEventHandler implements EventHandler<OrderEvent> {

    private OrderCreateListener bean;
    private RedisLockClient redisLockClient;

    @Override
    public void onEvent(OrderEvent event, long sequence, boolean endOfBatch) {
        log.info("event: {}, sequence: {}, endOfBatch: {}", event, sequence, endOfBatch);
        if (bean == null) {
            bean = SpringUtil.getBean(OrderCreateListener.class);
        }
//        OrderCreateListener bean = SpringUtil.getBean(OrderCreateListener.class);
        if (redisLockClient == null) {
            redisLockClient = SpringUtil.getBean(RedisLockClient.class);
        }
        redisLockClient.lockReentrant("order:create:promotion:" + event.getId(), 900L, 1000L, () -> {
            if (StrUtil.isNotBlank(event.getId())) {
                switch (event.getType()) {
                    case "pay" -> bean.userBalance(event.getId()); // 支付完成
                    case "complete" -> bean.commission(event.getId()); // 订单完成
                    case "voucher_commission" -> bean.voucherCommission(event.getId()); // 订单完成后抵用券佣金
                }
            }
            return true;
        });
    }

}